package com.get.backstage.user.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.get.backstage.user.entity.Menu;
import com.get.backstage.user.entity.Role;
import com.get.backstage.user.entity.User;
import com.get.backstage.user.service.MenuService;
import com.get.backstage.user.service.RoleService;
import com.get.backstage.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;


    @Override
    public User loadUserByUsername(String userName) {
        // 根据用户名获取用户
        User user = userService.getOne(new QueryWrapper<User>().eq("username", userName));
        if (user == null) {
            throw new BadCredentialsException("用户名或密码错误");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        // 获取user的权限标识。
        String[] roles = user.getRoleCodes().split(",");
        Arrays.stream(roles).forEach(roleCode -> {
            Role role = roleService.getOne(new QueryWrapper<Role>().eq("role_code", roleCode));
            String[] permissionCodes = role.getPermissionCodes().split(",");
            Arrays.stream(permissionCodes).forEach(permissionCode -> {
                Menu menu = menuService.getOne(new QueryWrapper<Menu>().eq("permission_code", permissionCode));
                String authority = menu.getPermissionIdentification();
                if (StrUtil.isNotBlank(authority)) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
                    grantedAuthorities.add(grantedAuthority);
                }
                user.setAuthorities(grantedAuthorities);
            });
        });

        return user;
    }


}